<script>
import { page, add, update, batchDelete } from '@/api/questionExamParams';
import { FilterMatchMode } from '@primevue/core/api';
import Button from 'primevue/button';
import InputText from 'primevue/inputtext';
import { useToast } from 'primevue/usetoast';
import Dropdown from 'primevue/dropdown';
import TreeSelect from 'primevue/treeselect';
import { listQuestionBank } from '@/api/questionBank';
import { useRouter } from 'vue-router';

export default {
    components: {
        InputText,
        Button,
        Dropdown,
        TreeSelect
    },
    data() {
        return {
            questionExamParams: [],
            questionExamParam: {
                id: null,
                questionBankId: null,
                questionBankName: null,
                totalScore: null,
                passScore: null,
                totalTime: null,
                questionCount: null,
                singleChoiceCount: null,
                multipleChoiceCount: null,
                singleChoiceScore: null,
                multipleChoiceScore: null,
                createTime: null,
                status: null
            },
            types: [
                { label: '单选题', value: 0 },
                { label: '多选题', value: 1 }
            ],
            statuses: [
                { label: '有效', value: 1 },
                { label: '无效', value: 0 }
            ],
            selectedQuestionExamParam: null,
            deleteQuestionDialog: false,
            deleteQuestionsDialog: false,
            loading: false,
            filters: {
                global: { value: null, matchMode: FilterMatchMode.CONTAINS }
            },
            pageSize: 10,
            pageNum: 1,
            totalRecords: 0,
            searchQuery: {
                questionBankId: null,
                status: null,
                id: null
            },
            selectedQuestionBank: null,
            questionBanks: [],
            questionExamParamDialog: false,
            submitting: false,
            dialogMode: 'add', // 'add' 或 'edit'
            submitted: false,
            formErrors: {},
            selectedBankForForm: null
        };
    },
    mounted() {
        this.loadQuestionExamParams();
        this.loadQuestionBanks();
    },
    methods: {
        async loadQuestionExamParams() {
            this.loading = true;
            try {
                const params = {
                    pageNum: this.pageNum,
                    pageSize: this.pageSize,
                    ...this.searchQuery
                };
                const response = await page(params);
                if (response.code === 200) {
                    this.questionExamParams = response.data.list || [];
                    this.totalRecords = response.data.total || 0;
                } else {
                    this.$toast.add({
                        severity: 'error',
                        summary: '加载失败',
                        detail: response.message || '无法加载题目数据',
                        life: 3000
                    });
                }
            } catch (error) {
                this.$toast.add({
                    severity: 'error',
                    summary: '加载失败',
                    detail: '无法加载题目数据',
                    life: 3000
                });
            } finally {
                this.loading = false;
            }
        },

        async loadQuestionBanks() {
            try {
                const response = await listQuestionBank({
                    pageNum: 1,
                    pageSize: 1000,
                    language: null
                });

                if (response.code === 200) {
                    this.questionBanks = (response.data || []).map((item) => ({
                        key: item.id.toString(),
                        label: item.name,
                        data: item.id
                    }));
                } else {
                    this.$toast.add({
                        severity: 'error',
                        summary: '加载失败',
                        detail: response.message || '无法加载题库数据',
                        life: 3000
                    });
                }
            } catch (error) {
                this.$toast.add({
                    severity: 'error',
                    summary: '加载失败',
                    detail: '无法加载题库数据',
                    life: 3000
                });
                console.error('加载题库失败:', error);
            }
        },

        resetSearch() {
            this.searchQuery = {
                questionBankId: null,
                status: null,
                id: null
            };
            this.selectedQuestionBank = null;
            this.loadQuestionExamParams();
        },

        onPage(event) {
            this.pageNum = event.page + 1;
            this.pageSize = event.rows;
            this.loadQuestionExamParams();
        },
        onSort(event) {
            let sortField = event.sortField;
            let sortOrder = event.sortOrder;
            if (sortField) {
                this.questionExamParams.sort((a, b) => {
                    let result = 0;
                    if (a[sortField] < b[sortField]) {
                        result = -1;
                    } else if (a[sortField] > b[sortField]) {
                        result = 1;
                    }
                    return sortOrder === 1 ? result : -result;
                });
            }
        },

        performSearch() {
            this.pageNum = 1;
            this.loadQuestionExamParams();
        },

        handleQuestionBankChange(value) {
            if (value && typeof value === 'object') {
                const keys = Object.keys(value);
                if (keys.length > 0) {
                    this.searchQuery.questionBankId = parseInt(keys[0]);
                } else {
                    this.searchQuery.questionBankId = null;
                }
            } else {
                this.searchQuery.questionBankId = value;
            }
        },

        confirmDeleteQuestionExamParam(activationCode) {
            this.questionExamParam = activationCode;
            this.deleteQuestionDialog = true;
        },

        async deleteQuestionExamParam() {
            try {
                this.loading = true;
                const response = await batchDelete([this.questionExamParam.id]);

                if (response.code === 200) {
                    this.$toast.add({
                        severity: 'success',
                        summary: '成功',
                        detail: '题目已删除',
                        life: 3000
                    });
                    this.deleteQuestionDialog = false;
                    this.loadQuestionExamParams();
                } else {
                    this.$toast.add({
                        severity: 'error',
                        summary: '失败',
                        detail: response.message || '删除题目失败',
                        life: 3000
                    });
                }
            } catch (error) {
                this.$toast.add({
                    severity: 'error',
                    summary: '错误',
                    detail: '删除题目时出错',
                    life: 3000
                });
                console.error('删除题目失败:', error);
            } finally {
                this.loading = false;
                this.deleteQuestionDialog = false;
            }
        },

        confirmDeleteSelected() {
            this.deleteQuestionsDialog = true;
        },

        async deleteSelectedQuestions() {
            try {
                this.loading = true;
                const ids = this.selectedQuestionExamParam.map((ac) => ac.id);
                const response = await batchDelete(ids);

                if (response.code === 200) {
                    this.$toast.add({
                        severity: 'success',
                        summary: '成功',
                        detail: '选中的题目已删除',
                        life: 3000
                    });
                    this.selectedQuestionExamParam = null;
                    this.deleteQuestionsDialog = false;
                    await this.loadQuestionExamParams();
                } else {
                    this.$toast.add({
                        severity: 'error',
                        summary: '失败',
                        detail: response.message || '批量删除题目失败',
                        life: 3000
                    });
                }
            } catch (error) {
                this.$toast.add({
                    severity: 'error',
                    summary: '错误',
                    detail: '批量删除题目时出错',
                    life: 3000
                });
                console.error('批量删除题目失败:', error);
            } finally {
                this.loading = false;
                this.deleteQuestionsDialog = false;
            }
        },

        exportCSV() {
            this.$refs.dt.exportCSV();
        },

        editQuestion(rowData) {
            this.questionExamParamForm = { ...rowData, adminNote: rowData.adminNote || '' };
            this.dialogMode = 'edit';
            this.questionExamParamDialog = true;
        },

        addQuestion() {
            this.questionExamParamForm = {
                id: null,
                questionBankId: null,
                questionBankName: '',
                totalScore: null,
                passScore: null,
                totalTime: null,
                questionCount: null,
                singleChoiceCount: null,
                multipleChoiceCount: null,
                singleChoiceScore: null,
                multipleChoiceScore: null,
                createTime: null,
                status: null,
                adminNote: ''
            };
            this.dialogMode = 'add';
            this.questionExamParamDialog = true;
        },

        async saveQuestionExamParam() {
            this.submitting = true;
            try {
                let response;
                if (this.dialogMode === 'add') {
                    response = await add(this.questionExamParamForm);
                } else if (this.dialogMode === 'edit') {
                    response = await update(this.questionExamParamForm);
                }
                if (response.code === 200) {
                    this.toast.add({
                        severity: 'success',
                        summary: '成功',
                        detail: this.dialogMode === 'add' ? '添加成功' : '更新成功',
                        life: 3000
                    });
                    this.questionExamParamDialog = false;
                    this.loadQuestionExamParams();
                } else {
                    this.toast.add({
                        severity: 'error',
                        summary: '失败',
                        detail: response.message || '操作失败',
                        life: 3000
                    });
                }
            } catch (error) {
                this.toast.add({
                    severity: 'error',
                    summary: '错误',
                    detail: '操作出错',
                    life: 3000
                });
                console.error('保存配置错误:', error);
            } finally {
                this.submitting = false;
            }
        },

        cancelDialog() {
            this.questionExamParamDialog = false;
        }
    },
    setup() {
        const toast = useToast();
        const router = useRouter();
        return { toast, router };
    }
};
</script>

<template>
    <div>
        <div class="card">
            <Toast />
            <Toolbar class="mb-6">
                <template #start>
                    <Button label="批量删除" icon="pi pi-trash" severity="secondary" @click="confirmDeleteSelected" :disabled="!selectedQuestionExamParam || !selectedQuestionExamParam.length" />
                </template>
                <template #end>
                    <Button label="新建考试配置" icon="pi pi-plus" severity="primary" class="mr-2" @click="addQuestion" />
                    <Button label="导出" icon="pi pi-upload" severity="secondary" @click="exportCSV($event)" />
                </template>
            </Toolbar>
            <Toolbar>
                <template #start>
                    <div class="flex flex-wrap items-center gap-2">
                        <FloatLabel variant="on">
                            <InputText id="on_label" v-model="searchQuery.id" />
                            <label for="on_label">搜索考试配置ID</label>
                        </FloatLabel>
                        <TreeSelect v-model="selectedQuestionBank" :options="questionBanks" selectionMode="single" placeholder="选择题库" class="mr-2 w-12rem" :filter="true" :showClear="true" @update:modelValue="handleQuestionBankChange" />
                        <Dropdown v-model="searchQuery.status" :options="statuses" optionLabel="label" optionValue="value" placeholder="选择状态" class="mr-2" :showClear="true" />
                        <Button v-if="Object.values(searchQuery).some((value) => value !== null && value !== '')" label="重置" icon="pi pi-eraser" severity="info" @click="resetSearch" color="mr-2" />
                    </div>
                </template>
                <template #end>
                    <Button label="搜索" icon="pi pi-search" @click="performSearch" />
                </template>
            </Toolbar>
            <DataTable
                ref="dt"
                stripedRows
                v-model:selection="selectedQuestionExamParam"
                :value="questionExamParams"
                dataKey="id"
                :paginator="true"
                :rows="pageSize"
                lazy
                :totalRecords="totalRecords"
                scrollable
                :loading="loading"
                @page="onPage($event)"
                @sort="onSort($event)"
                :filters="filters"
                paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
                :rowsPerPageOptions="[5, 10, 20, 50]"
                currentPageReportTemplate="显示 {first} 到 {last} 共 {totalRecords} 条记录"
            >
                <template #header>
                    <h4 class="m-0">题目中心</h4>
                </template>

                <Column selectionMode="multiple" style="width: 3rem" :exportable="false"></Column>
                <Column field="id" frozen header="ID" sortable style="min-width: 5rem" bodyClass="text-center"></Column>
                <Column field="questionBankName" header="题库名称" sortable style="min-width: 16rem" bodyClass="text-center"></Column>
                <Column field="totalScore" header="考试总分" sortable style="min-width: 10rem" bodyClass="text-center"></Column>
                <Column field="passScore" header="及格分数" sortable style="min-width: 10rem" bodyClass="text-center"></Column>
                <Column field="totalTime" header="考试总时长" sortable style="min-width: 10rem" bodyClass="text-center">
                    <template #body="{ data }">
                        {{ data.totalTime ? `${data.totalTime} 分钟` : '未设置' }}
                    </template>
                </Column>
                <Column field="questionCount" header="题目总数" sortable style="min-width: 10rem" bodyClass="text-center"></Column>
                <Column field="singleChoiceCount" header="单选题数量" sortable style="min-width: 10rem" bodyClass="text-center"></Column>
                <Column field="multipleChoiceCount" header="多选题数量" sortable style="min-width: 10rem" bodyClass="text-center"></Column>
                <Column field="singleChoiceScore" header="单选题分数" sortable style="min-width: 10rem" bodyClass="text-center"></Column>
                <Column field="multipleChoiceScore" header="多选题分数" sortable style="min-width: 10rem" bodyClass="text-center"></Column>
                <Column field="createTime" header="创建时间" sortable style="min-width: 16rem" bodyClass="text-center">
                    <template #body="{ data }">
                        {{ data.createTime ? new Date(data.createTime).toLocaleString() : '未设置' }}
                    </template>
                </Column>
                <Column field="status" header="状态" sortable style="min-width: 10rem" bodyClass="text-center">
                    <template #body="slotProps">
                        <Tag :severity="slotProps.data.status === 1 ? 'info' : 'secondary'" :value="statuses.find((s) => s.value === slotProps.data.status)?.label || '未知'" />
                    </template>
                </Column>
                <Column frozen alignFrozen="right" header="操作" :exportable="false" style="min-width: 8rem">
                    <template #body="slotProps">
                        <div class="flex gap-2">
                            <Button icon="pi pi-pencil" text rounded severity="info" @click="editQuestion(slotProps.data)" v-tooltip.top="'编辑配置'" />
                            <Button icon="pi pi-trash" text rounded severity="danger" @click="confirmDeleteQuestionExamParam(slotProps.data)" v-tooltip.top="'删除配置'" />
                        </div>
                    </template>
                </Column>
            </DataTable>
        </div>
        <!-- 新增和修改对话框 -->
        <Dialog v-model:visible="questionExamParamDialog" :header="dialogMode === 'add' ? '新增考试配置' : '编辑考试配置'" :modal="true">
            <div class="p-fluid">
                <div class="field mb-4">
                    <label for="questionBank" class="font-bold mb-2 block">题库名称</label>
                    <TreeSelect id="questionBank" v-model="selectedBankForForm" :options="questionBanks" selectionMode="single"
                        placeholder="选择题库" :filter="true" :showClear="true" class="w-full"
                        :class="{ 'p-invalid': submitted && !selectedBankForForm }" />
                    <small v-if="submitted && !selectedBankForForm" class="p-error">请选择题库</small>
                </div>

                <!-- 考试基本设置卡片 -->
                <div class="surface-card border-round shadow-1 my-4">
                    <h3 class="text-lg font-semibold mb-3">考试基本设置</h3>
                    <div class="flex flex-row gap-4">
                        <div class="col-span-6">
                            <div class="field">
                                <label for="totalScore" class="font-bold mb-2 block">考试总分</label>
                                <InputText id="totalScore" v-model.number="questionExamParamForm.totalScore" type="number" min="0"
                                    :class="{ 'p-invalid': submitted && !questionExamParamForm.totalScore }" />
                                <small v-if="submitted && !questionExamParamForm.totalScore" class="p-error">请输入考试总分</small>
                            </div>
                        </div>
                        <div class="col-span-6">
                            <div class="field">
                                <label for="passScore" class="font-bold mb-2 block">及格分数 *</label>
                                <InputText id="passScore" v-model.number="questionExamParamForm.passScore" type="number" min="0"
                                    :class="{ 'p-invalid': submitted && !questionExamParamForm.passScore }" />
                                <small v-if="submitted && !questionExamParamForm.passScore" class="p-error">请输入及格分数</small>
                            </div>
                        </div>
                        <div class="">
                            <div class="field">
                                <label for="totalTime" class="font-bold mb-2 block">考试总时长（分钟）*</label>
                                <InputText id="totalTime" v-model.number="questionExamParamForm.totalTime" type="number" min="0"
                                    :class="{ 'p-invalid': submitted && !questionExamParamForm.totalTime }" />
                                <small v-if="submitted && !questionExamParamForm.totalTime" class="p-error">请输入考试时长</small>
                            </div>
                        </div>
                        <div class="">
                            <div class="field">
                                <label for="status" class="font-bold mb-2 block">状态 *</label>
                                <Dropdown id="status" v-model="questionExamParamForm.status" :options="statuses" optionLabel="label" optionValue="value"
                                    placeholder="选择状态" :class="{ 'p-invalid': submitted && questionExamParamForm.status === null }" />
                                <small v-if="submitted && questionExamParamForm.status === null" class="p-error">请选择状态</small>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 题目设置卡片 -->
                <div class="surface-card border-round shadow-1">
                    <h3 class="text-lg font-semibold mb-3">题目设置</h3>
                    <div class="flex flex-row gap-4">
                        <div class="">
                            <div class="field">
                                <label for="questionCount" class="font-bold mb-2 block">题目总数</label>
                                <InputText id="questionCount" v-model.number="questionExamParamForm.questionCount" type="number" min="0"/>
                            </div>
                        </div>


                            <div class="grid">
                                <div class="col-12 md:col-6">
                                    <div class="field">
                                        <label for="singleChoiceCount" class="font-bold mb-2 block">单选题数量 *</label>
                                        <InputText id="singleChoiceCount" v-model.number="questionExamParamForm.singleChoiceCount" type="number" min="0"
                                            :class="{ 'p-invalid': submitted && !questionExamParamForm.singleChoiceCount }" />
                                        <small v-if="submitted && !questionExamParamForm.singleChoiceCount" class="p-error">请输入单选题数量</small>
                                    </div>
                                </div>

                                <div class="col-12 md:col-6 mt-4">
                                    <div class="field">
                                        <label for="singleChoiceScore" class="font-bold mb-2 block">单选题分数 *</label>
                                        <InputText id="singleChoiceScore" v-model.number="questionExamParamForm.singleChoiceScore" type="number" min="0"
                                            :class="{ 'p-invalid': submitted && !questionExamParamForm.singleChoiceScore }" />
                                        <small v-if="submitted && !questionExamParamForm.singleChoiceScore" class="p-error">请输入单选题分数</small>
                                    </div>
                                </div>
                            </div>

                            <div class="grid">
                                <div class="col-12 md:col-6">
                                    <div class="field">
                                        <label for="multipleChoiceCount" class="font-bold mb-2 block">多选题数量 *</label>
                                        <InputText id="multipleChoiceCount" v-model.number="questionExamParamForm.multipleChoiceCount" type="number" min="0"
                                            :class="{ 'p-invalid': submitted && !questionExamParamForm.multipleChoiceCount }" />
                                        <small v-if="submitted && !questionExamParamForm.multipleChoiceCount" class="p-error">请输入多选题数量</small>
                                    </div>
                                </div>
                                <div class="col-12 md:col-6 mt-4">
                                    <div class="field">
                                        <label for="multipleChoiceScore" class="font-bold mb-2 block">多选题分数 *</label>
                                        <InputText id="multipleChoiceScore" v-model.number="questionExamParamForm.multipleChoiceScore" type="number" min="0"
                                            :class="{ 'p-invalid': submitted && !questionExamParamForm.multipleChoiceScore }" />
                                        <small v-if="submitted && !questionExamParamForm.multipleChoiceScore" class="p-error">请输入多选题分数</small>
                                    </div>
                                </div>
                            </div>

                    </div>
                </div>
            </div>
            <template #footer>
                <Button label="取消" icon="pi pi-times" text @click="cancelDialog" />
                <Button label="保存" icon="pi pi-check" severity="primary" :loading="submitting" @click="saveQuestionExamParam" />
            </template>
        </Dialog>
        <!-- 删除确认对话框 -->
        <Dialog v-model:visible="deleteQuestionDialog" :style="{ width: '450px' }" header="确认删除" :modal="true">
            <div class="flex items-center gap-4">
                <i class="pi pi-exclamation-triangle !text-3xl" />
                <span v-if="questionExamParam"
                    >确定要删除配置 <b>{{ questionExamParam.id }}</b> 吗？</span
                >
            </div>
            <template #footer>
                <Button label="取消" icon="pi pi-times" text @click="deleteQuestionDialog = false" />
                <Button label="确定" icon="pi pi-check" severity="danger" @click="deleteQuestionExamParam" />
            </template>
        </Dialog>

        <!-- 批量删除确认对话框 -->
        <Dialog v-model:visible="deleteQuestionsDialog" :style="{ width: '450px' }" header="确认删除" :modal="true">
            <div class="flex items-center gap-4">
                <i class="pi pi-exclamation-triangle !text-3xl" />
                <span>确定要删除选中的题目吗？</span>
            </div>
            <template #footer>
                <Button label="取消" icon="pi pi-times" text @click="deleteQuestionsDialog = false" />
                <Button label="确定" icon="pi pi-check" severity="danger" @click="deleteSelectedQuestions" />
            </template>
        </Dialog>
    </div>
</template>
